﻿using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using WhaleAccount.Contracts.ViewModels;
using WhaleAccount.Contracts.Services;
using WhaleAccount.Models;

namespace WhaleAccount.ViewModels;
public class BillViewModel : ObservableRecipient, INavigationAware
{
    private readonly IRecordService recordService;
    private YearRecordSummary yearRecordSummary;
    private MonthRecordSummary? _selected;

    public YearRecordSummary YearRecordSummary
    {
        get => yearRecordSummary;
        set => SetProperty(ref yearRecordSummary, value);
    }
    public MonthRecordSummary? Selected
    {
        get => _selected;
        set => SetProperty(ref _selected, value);
    }
    public ObservableCollection<MonthRecordSummary> MonthRecordSummaryList
    {
        get;
        private set;
    } = new ObservableCollection<MonthRecordSummary>();

    public BillViewModel(IRecordService recordService)
    {
        this.recordService = recordService;
        yearRecordSummary = new YearRecordSummary();
    }


    public void OnNavigatedFrom()
    {
    }
    public void OnNavigatedTo(object parameter)
    {
        LoadData(DateTime.Now.Year);
    }

    public async void LoadData(int year)
    {
        MonthRecordSummaryList.Clear();

        var data = await recordService.GetMonthRecordSummaryListAsync(year);
        double income = 0;
        double expense = 0;
        double balance = 0;

        foreach (var record in data)
        {
            MonthRecordSummaryList.Add(record);

            income += record.Income;
            expense += record.Expense;
            balance += record.Balance;
        }

        yearRecordSummary.Income = income;
        yearRecordSummary.Expense = expense;
        yearRecordSummary.Balance = balance;
    }

    public void EnsureItemSelected()
    {
        if (MonthRecordSummaryList.Count > 0)
        {
            Selected ??= MonthRecordSummaryList.First();
        }
    }
}
